package cn.ztr.ymcc.web.controller;

import cn.ztr.ymcc.constance.LoginCons;
import cn.ztr.ymcc.domain.Login;
import cn.ztr.ymcc.service.IShopCarService;
import cn.ztr.ymcc.domain.ShopCar;
import cn.ztr.ymcc.query.ShopCarQuery;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.result.PageList;
import cn.ztr.ymcc.util.AssertUtil;
import cn.ztr.ymcc.utils.LoginContextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/shopCar")
public class ShopCarController {

    @Autowired
    public IShopCarService shopCarService;
    @Autowired
    private LoginContextUtils loginContextUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String SHOP_CAR_KEY="SHOP_CAR_KEY:";

    /**
    * 添加到购物车
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody ShopCar shopCar, HttpServletRequest request) throws Exception {

         JSONObject result = (JSONObject) loginContextUtils.getLoginUser(request.getHeader(LoginCons.TOKEN));
        Login login = JSON.parseObject(JSON.toJSONString(result), Login.class);
        if(shopCar.getId()!=null){
            shopCarService.updateById(shopCar);
        }else{
            //做幂等性校验
            String key = SHOP_CAR_KEY+login.getId()+":"+shopCar.getCourseId();
            Object o = redisTemplate.opsForValue().get(key);
            AssertUtil.isTrue(o==null,"请勿重复添加商品,去下单购买吧~");
            redisTemplate.opsForValue().set(key,"1",10, TimeUnit.DAYS);
            shopCarService.add(shopCar,login);
        }
        return JsonResult.me();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        shopCarService.removeById(id);
        return JsonResult.me();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.me().setData(shopCarService.getById(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.me().setData(shopCarService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody ShopCarQuery query){
        Page<ShopCar> page = new Page<ShopCar>(query.getPageNo(), query.getPageSize());
        page = shopCarService.page(page);
        return JsonResult.me().setData(new PageList<ShopCar>(page.getTotal(), page.getRecords()));
    }

    @GetMapping("/listForUser")
    public JsonResult listForUser(HttpServletRequest request) throws Exception {
        Long loginId  = loginContextUtils.getUserId(request.getHeader(LoginCons.TOKEN));
        List<ShopCar> shopCars = shopCarService.list(new QueryWrapper<ShopCar>().eq("user_id", loginId));
        return JsonResult.me(shopCars);
    }
}
